# -*- coding: utf-8 -*-

"""HTMLTestRunner 截图版 selenium 版"""
import time
import unittest, os
from selenium import webdriver
from Basic.HTMLTestRunner_log_cn import HTMLTestRunner
from Basic.PATH import log_path, UiniTest_path
from Basic.base_log import log
from Basic.getProcess import judgeprocess

class HTMLReportTest():

    def __init__(self):
        pass

    def HTMLtest_main(self, datatime, Testpy):

        log.info('------------测试初始化------------')
        ''' discover()方法有3个参数  
        start_dir表示测试的模块名称或者测试用例的目录
        pattern='test*.py'表示测试用例文件名的匹配规则，请注意文件名以test开头
        top_level_dir=NONE表示测试模块的顶层目录
        '''
        # 测试日志、报告输出路径
        self.report_Path = os.path.join(log_path, 'UniTestReport ' + str(datatime) + ".html")
        log.info('测试报告输出路径 ReportPath : %s' % self.report_Path)
        reportwrite = open(self.report_Path, 'wb')
        # 获取HTML框架：retry=0  测试失败重试次数。save_last_try=False，则显示所有重试的结果。=1则显示最后一次重试结果。
        runner = HTMLTestRunner(title="UI自动化测试报告", description="UI自动化测试报告", stream=reportwrite, verbosity=2,
                                retry=0, save_last_try=False, custom_logger=log)
        # 添加测试套件
        log.info('测试框架框架所在文件路径 UiniTest_path : %s\\%s.py' % (UiniTest_path,Testpy))
        discover = unittest.defaultTestLoader.discover(UiniTest_path, pattern='%s*.py' % Testpy)
        # pattern：在同一目录中自动加载符合文件名的测试用例。
        log.info('测试用例套件 discover : %s' % discover)
        # 运行HTML框架
        runner.run(discover)
        reportwrite.close()
        # 打开测试报告
        # self.open_report()
    def open_report(self, datatime):
        # 判断seleium运行结束
        while judgeprocess('chromedriver.exe'):
            time.sleep(1)
        # 启动seleium
        driver = webdriver.Chrome()
        driver.maximize_window()
        driver.get(self.report_Path)
        # 获取页面句柄
        handle = driver.current_window_handle
        # 判断页面存在则关闭程序
        while self.get_handle(driver) == handle:
            # print('当前页面：%s' % handle)
            pass
        print('该页面已关闭：%s' % handle)
        driver.quit()
        # 强制关闭进程
        os.system('taskkill /IM chromedriver.exe /F')

    def get_handle(self, driver):
        try:
            # print('get :%s ' % handle)
            return driver.current_window_handle
        except:
            return None



if __name__ == "__main__":
    pass
    # unittest.main()
    # HTMLReportTest().open_report('2020-03-26 14.38.33')
